package com.sixmac.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.constant.Const;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.kit.LogKit;
import com.sixmac.core.toolbox.kit.RandomKit;
import com.sixmac.module.Contract;
import com.sixmac.module.Room;
import com.sixmac.module.Tenant;
import com.sixmac.module.TenantRoom;
import com.sixmac.platform.service.LoginService;
import com.sixmac.util.SMS;
import com.sixmac.util.WeChatConfig;
import com.sixmac.utils.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created by admin on 2018/9/4.
 */
@Service
public class LoginServiceImpl extends BaseService<Tenant> implements LoginService {
    @Autowired
    WeChatConfig weChatConfig;
    private static final String LOGIN = "1";

    public AjaxResult login(String code, String nickname) {

        AjaxResult res = new AjaxResult();
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = weChatConfig.getAppId();
        // String wxspAppid = "wx0cc3a5d6d43a61e2";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = weChatConfig.getSecret();
        //String wxspSecret = "461b79aacda17f8e0805d713242d7c77";
        //授权（必填）
        String grant_type = "authorization_code";
        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JsonKit.parse(sr);
        //获取会话密钥（session_key）
        //  String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openId = (String) json.get("openid");
        if (openId == null){
            res.setCode(1);
            return res;
        }
//        String openId = "123123324";
        Tenant tenant = this.findFirstBy("wechatKey=#{wechatKey}", getData("wechatKey", openId));
        if (tenant == null) {
            tenant = new Tenant();
            tenant.setStatus(1);
            tenant.setWechatKey(openId);
            tenant.setCreateDate(new Date());
            if (!Strings.isNullOrEmpty(nickname))
                tenant.setNickname(nickname);
            this.saveAndSetKey(tenant);
        }
        String token = UUID.randomUUID().toString();
        CacheKit.put(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, token, tenant);
        tenant.setToken(token);
        res.setCode(0);

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId="+tenant.getId(),null);
        HashMap data = getData("landlord", tenant);
        if (tenantRoom!=null){
            Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());
            data.put("room",room);
        }

        data.put("inStatus",0);
        if (tenantRoom!=null){
            data.put("inStatus",1);
        }

        data.put("isAdmin",0);
        if (tenantRoom!=null&&tenantRoom.getIsAdmin()!=null&&tenantRoom.getIsAdmin()==2){
            data.put("isAdmin",1);
        }

        data.put("isApply",0);
        if (tenantRoom!=null){
            tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" isAdmin = 2 and roomId = "+tenantRoom.getRoomId()+" and status = 1 ",null);
            if (tenantRoom!=null){
                data.put("isApply",0);
            }else{
                data.put("isApply",1);
            }
        }

        return res.setData(data);
    }

    public AjaxResult sendCaptcha(String phone) {
        // 生成验证码
        String code = RandomKit.randomNumbers(6);
        return this.sendCapcha(LOGIN, code, phone);
    }


    private void clearCaptcha(String mobile, String type) {
        CacheKit.remove(ConstCache.CAPTCHA, mobile + "_" + type);
        CacheKit.remove(ConstCache.CAPTCHA_COUNT, mobile + "_" + type);
    }

    private Boolean verifyCaptcha(String oldCaptcha, String mobile, String type) {
        String _key = mobile + "_" + type;
        String captcha = CacheKit.get(ConstCache.CAPTCHA, _key);
        if (captcha == null) {
            return false;
        }
        if (captcha.equals(oldCaptcha)) {
            return true;
        }
        return false;
    }


    private AjaxResult sendCapcha(String type, String message, String mobile) {
        AjaxResult res = AjaxResult.initAjaxResult();
        String _key = mobile + "_" + type;
        Integer count = CacheKit.get(ConstCache.CAPTCHA_COUNT, _key);
        //Const.CAPTCHA_COUNT 最大限制数量
        if (count == Const.CAPTCHA_COUNT) {
            return res.addError("已超出最大限制条数，请稍后再试");
        }
        if (count == null) {
            count = 0;
        }
        String oldCode = CacheKit.get(ConstCache.CAPTCHA, _key);
        if (oldCode == null || oldCode.equals("")) {
            CacheKit.put(ConstCache.CAPTCHA, _key, message);
            oldCode = message;
        }
        //发送·验证法
        CacheKit.put(ConstCache.CAPTCHA_COUNT, _key, ++count);
        LogKit.error("发送的验证码是:" + oldCode + "条数:" + count);

        SMS.send(mobile,oldCode,"60");
        //
        // SendMsgUtil.sendSms(oldCode, String.valueOf(mobile));
        return res.setData(CMap.init().put("captcha", oldCode));
    }


    public AjaxResult bindMobile(Tenant tenant, String phone, String captcha) {

        AjaxResult res = new AjaxResult();
        //验证通过
        if (this.verifyCaptcha(captcha, phone, LOGIN)) {
            //清除缓存
            this.clearCaptcha(phone, LOGIN);
            Tenant l = this.findFirstBy("mobile=#{mobile}", getData("mobile", phone));
            if (l != null && !Strings.isNullOrEmpty(tenant.getWechatKey()))
                return error("此手机号码已经绑定其他微信号");
            tenant = this.findById(tenant.getId());
            tenant.setMobile(phone);
            this.update(tenant);
            return success("绑定成功");
        } else {
            return error("验证码错误");
        }
    }


}
